/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lovetransferjia.chatuidemo.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.util.HanziToPinyin;
import com.lovetransferjia.chatuidemo.Constant;
import com.lovetransferjia.chatuidemo.MyApplication;
import com.lovetransferjia.chatuidemo.R;
import com.lovetransferjia.chatuidemo.domain.User;
import com.lovetransferjia.chatuidemo.jia.utility.ConnectionDetector;
import com.lovetransferjia.chatuidemo.jia.utility.Utility;
import com.lovetransferjia.chatuidemo.utils.CommonUtils;
import com.renn.rennsdk.RennClient;
import com.renn.rennsdk.RennClient.LoginListener;
import com.renn.rennsdk.RennExecutor.CallBack;
import com.renn.rennsdk.RennResponse;
import com.renn.rennsdk.param.GetUserParam;
import com.umeng.analytics.MobclickAgent;

/**
 * 登陆页面
 * 
 */
public class LoginActivity extends BaseActivity {
	
	ProgressDialog pd=null;
	public Context context = this;
	String lovename = "";
	String lovepwd = "";
	private final String mPageName = "login";
	Context mContext = this;
	private ImageButton renrenButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		
		renrenButton = (ImageButton) findViewById(R.id.renrenlogin);

		MobclickAgent.setDebugMode(true);
		// SDK在统计Fragment时，需要关闭Activity自带的页面统计，
		// 然后在每个页面中重新集成页面统计的代码(包括调用了 onResume 和 onPause 的Activity)。
		MobclickAgent.openActivityDurationTrack(false);
		// MobclickAgent.setAutoLocation(true);
		// MobclickAgent.setSessionContinueMillis(1000);

		MobclickAgent.updateOnlineConfig(this);
		// 人人
		final RennClient rennClient = MyApplication.rennClient;
		renrenButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				rennClient.login((Activity) mContext);
				pd = new ProgressDialog(context);
				pd.setMessage("正在登录...");
				pd.show();
			}
		});
		rennClient.setLoginListener(new LoginListener() {
			@Override
			public void onLoginSuccess() {
				// TODO Auto-generated method stub
				GetUserParam param = new GetUserParam();
				try {
					rennClient.getRennService().sendAsynRequest(param,
							new CallBack() {
								@Override
								public void onSuccess(RennResponse response) {
									// TODO Auto-generated method stub
									if(pd!=null)
									pd.dismiss();
									try {
										MyApplication.rennClient.setAccessToken(rennClient.getAccessToken());
										Log.e("login status",
												response.getResponseObject().toString());
										JSONObject rJsonObject = response
												.getResponseObject();
										JSONArray edujsonArray = rJsonObject
												.getJSONArray("education");
										List<NameValuePair> info = new ArrayList<NameValuePair>();

										info.add(new BasicNameValuePair("name",
												rJsonObject.getString("name")));

										if (edujsonArray.length() > 0) {
											info.add(new BasicNameValuePair(
													"school", edujsonArray
															.getJSONObject(0)
															.getString("name")));
											info.add(new BasicNameValuePair(
													"year", edujsonArray
															.getJSONObject(0)
															.getString("year")));
											info.add(new BasicNameValuePair(
													"major",
													edujsonArray.getJSONObject(
															0).getString(
															"department")));
											info.add(new BasicNameValuePair(
													"edu",
													edujsonArray
															.getJSONObject(0)
															.getString(
																	"educationBackground")));
										} else {
											info.add(new BasicNameValuePair(
													"school", null));
											info.add(new BasicNameValuePair(
													"year", null));
											info.add(new BasicNameValuePair(
													"major", null));
											info.add(new BasicNameValuePair(
													"edu", null));
										}
										JSONObject basJsonObject = rJsonObject
												.getJSONObject("basicInformation");
										if (basJsonObject.getString("sex").equals("MALE")) {
											info.add(new BasicNameValuePair(
													"gender", "1"));
										} else if (basJsonObject
												.getString("sex").equals("FEMALE")) {
											info.add(new BasicNameValuePair(
													"gender", "0"));
										} else {
											info.add(new BasicNameValuePair(
													"gender", "0"));
										}
										info.add(new BasicNameValuePair(
												"renrenid", rJsonObject
														.getString("id")));
										info.add(new BasicNameValuePair(
												"headimage", rJsonObject
														.getJSONArray("avatar")
														.getJSONObject(3)
														.getString("url")));
										lovename = rJsonObject.getString("id");
										lovepwd = "renrenid";
										new renrenGo().execute(info);
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}

								@Override
								public void onFailed(String errorCode,
										String errorMessage) {
									Toast.makeText(getApplicationContext(), "人人登录错误", Toast.LENGTH_LONG);
									// TODO Auto-generated method stub
									if(pd!=null)
									pd.dismiss();
								}
							});
				} catch (Exception e) {
					Log.d("renren servce", e.toString());
					Toast.makeText(getApplicationContext(), "人人登录错误:"+e.toString(), Toast.LENGTH_LONG);
					// TODO Auto-generated method stub
					if(pd!=null)
					pd.dismiss();
				}
			}

			@Override
			public void onLoginCanceled() {
				// TODO Auto-generated method stub
				if(pd!=null)
				pd.dismiss();
			}

		});
		
		
	}

	public class renrenGo extends AsyncTask<List<NameValuePair>, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			Log.d("loginTask", "pre");
			pd = new ProgressDialog(context);
			pd.setMessage("正在登录...");
			pd.show();
			Log.d("loginTask", "preend");
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.d("loginTask", "posts");
			
			
				
				if (result = true && MyApplication.id != null) {

					final String username = MyApplication.id;
					final String password = "love" + MyApplication.id;
					Log.e("first in login",first);
					if(first.equals("0")){
						
					EMChatManager.getInstance().login(username, password,
							new EMCallBack() {
								@Override
								public void onSuccess() {
									// 登陆成功，保存用户名密码
									MyApplication.getInstance().setUserName(
											username);
									Log.d("name", username);
									MyApplication.getInstance().setPassword(
											password);
									Log.d("pwd", password);
									if (lovename.length() > 0)
										MyApplication.getInstance().setLoveName(
												lovename);
									Log.d("lovename", lovename);
									if (lovepwd.length() > 0)
										MyApplication.getInstance().setLovepwd(
												lovepwd);
									Log.d("lovepwd", lovepwd);
									if (!LoginActivity.this.isFinishing())
										if(pd!=null)
										pd.dismiss();
									// 进入主页面
									Intent intent = new Intent(LoginActivity.this,
											MainActivity.class);
									intent.putExtra("status", "login");
									startActivity(intent);
									if(pd!=null)
										pd.dismiss();
									finish();
								}

								@Override
								public void onProgress(int progress, String status) {

								}

								@Override
								public void onError(int code, final String message) {

									runOnUiThread(new Runnable() {
										public void run() {
											if(pd!=null)
												pd.dismiss();
											
											Toast.makeText(getApplicationContext(),
													"登录失败: " + message, 0).show();
										}
									});
								}
							});
					}else{
					
						new EaseMobRegister().execute(username,password);
					}
					
				

			} else {
				if(pd!=null)
					pd.dismiss();
				Toast.makeText(MyApplication.applicationContext, failString,
						Toast.LENGTH_SHORT).show();
			}
		}

		String urlString = MyApplication.baseUrl + "user/renren"
				+ MyApplication.postfix;
		String statusString = "", failString = "用户名或密码错误";
		String first="",id="";
		@Override
		protected Boolean doInBackground(List<NameValuePair>... para) {

			try {
				JSONObject jsonObject = Utility.PostSimple(urlString, para[0],
						statusString, failString);
				if (jsonObject.getString("status").equals("success")){
					first=jsonObject.getString("first");
					id=jsonObject.getString("id");
					MyApplication.id=id;
					Log.e("first",first);
					return true;
				}
				else {
					failString = jsonObject.getString("status");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				failString = e.toString();
			}
			return false;
		}

	}

	public class LoginTask extends AsyncTask<String, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			Log.d("loginTask", "pre");
			pd = new ProgressDialog(context);
			pd.setMessage("正在登录...");
			pd.show();
			Log.d("loginTask", "preend");
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.d("loginTask", "posts");
			if (result = true && MyApplication.id != null) {

				final String username = MyApplication.id;
				final String password = "love" + MyApplication.id;
				
					
				EMChatManager.getInstance().login(username, password,
						new EMCallBack() {
							@Override
							public void onSuccess() {
								// 登陆成功，保存用户名密码
								MyApplication.getInstance().setUserName(
										username);
								Log.d("name", username);
								MyApplication.getInstance().setPassword(
										password);
								Log.d("pwd", password);
								if (lovename.length() > 0)
									MyApplication.getInstance().setLoveName(
											lovename);
								Log.d("lovename", lovename);
								if (lovepwd.length() > 0)
									MyApplication.getInstance().setLovepwd(
											lovepwd);
								Log.d("lovepwd", lovepwd);
								if (!LoginActivity.this.isFinishing())
									if(pd!=null)
									pd.dismiss();
								// 进入主页面
								Intent intent = new Intent(LoginActivity.this,
										MainActivity.class);
								intent.putExtra("status", "login");
								startActivity(intent);
								if(pd!=null)
									pd.dismiss();
								finish();
							}

							@Override
							public void onProgress(int progress, String status) {

							}

							@Override
							public void onError(int code, final String message) {

								runOnUiThread(new Runnable() {
									public void run() {
										if(pd!=null)
										pd.dismiss();
										Toast.makeText(getApplicationContext(),
												"登录失败: " + message, 0).show();
									}
								});
							}
						});
				}else {
				if(pd!=null)
				pd.dismiss();
				Toast.makeText(MyApplication.applicationContext, failString,
						Toast.LENGTH_SHORT).show();
			}
		}

		String urlString = MyApplication.baseUrl + "user/login"
				+ MyApplication.postfix;
		String statusString = "", failString = "用户名或密码错误";

		@Override
		protected Boolean doInBackground(String... args) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("Email", args[0]));
			params.add(new BasicNameValuePair("password", args[1]));

			try {
				JSONObject jsonObject = Utility.PostSimple(urlString, params,
						statusString, failString);
				if (jsonObject.getString("status").equals("success")){
					MyApplication.id=jsonObject.getString("id");
				
					return true;
				}
				else {
					failString = jsonObject.getString("status");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				failString = e.toString();
			}
			return false;
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		// 如果用户名密码都有，直接进入主页面
		MobclickAgent.onPageStart(mPageName);
		MobclickAgent.onResume(mContext);

		String lovenamee = MyApplication.getInstance().getLoveName();
		String lovepwde = MyApplication.getInstance().getLovepwd();
		Log.d("login resume", "sss" + lovenamee + lovepwde
				+ MyApplication.getInstance().getUserName()
				+ MyApplication.getInstance().getPassword());
		if (lovenamee != null && lovepwde != null) {
			new LoginTask().execute(lovenamee, lovepwde);
		}
		ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
		cd.isConnectingToInternet(); // true or false
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(mPageName);
		MobclickAgent.onPause(mContext);
	}

	/**
	 * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
	 * 
	 * @param username
	 * @param user
	 */
	protected void setUserHearder(String username, User user) {
		String headerName = null;
		if (!TextUtils.isEmpty(user.getNick())) {
			headerName = user.getNick();
		} else {
			headerName = user.getUsername();
		}
		if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
			user.setHeader("");
		} else if (Character.isDigit(headerName.charAt(0))) {
			user.setHeader("#");
		} else {
			user.setHeader(HanziToPinyin.getInstance()
					.get(headerName.substring(0, 1)).get(0).target.substring(0,
					1).toUpperCase());
			char header = user.getHeader().toLowerCase().charAt(0);
			if (header < 'a' || header > 'z') {
				user.setHeader("#");
			}
		}
	}
	
	public class EaseMobRegister extends AsyncTask<String ,Void,Boolean>{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pd = new ProgressDialog(context);
			pd.setMessage("正在登录...");
			pd.show();
		}
		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			
			Log.d("EaseMobRegister", "onpostExecute"+result);
			if(result==false){
				if(pd!=null)
					pd.dismiss();
				String errorMsg = failString;
				if (errorMsg.indexOf("EMNetworkUnconnectedException") != -1) {
					Toast.makeText(getApplicationContext(), "网络异常，请检查网络！", 0).show();
				} else if (errorMsg.indexOf("conflict") != -1) {
					Toast.makeText(getApplicationContext(), "用户已存在！", 0).show();
				} else if (errorMsg.indexOf("not support the capital letters") != -1) {
					Toast.makeText(getApplicationContext(), "用户名不支持大写字母！", 0).show();
				} else {
					Toast.makeText(getApplicationContext(), "注册失败，过会儿再试试？: " + errorMsg, 1).show();
				}
			}else{
				Toast.makeText(getApplicationContext(), " 注册成功", 0).show();
				final String username=MyApplication.id;
				final String password="love"+MyApplication.id;
				EMChatManager.getInstance().login(username, password, new EMCallBack() {

					@Override
					public void onSuccess() {
						// 登陆成功，保存用户名密码
						// 登陆成功，保存用户名密码
						MyApplication.getInstance().setUserName(
								username);
						MyApplication.getInstance().setPassword(
								password);
						if (lovename.length() > 0)
							MyApplication.getInstance().setLoveName(
									lovename);
						if (lovepwd.length() > 0)
							MyApplication.getInstance().setLovepwd(
									lovepwd);
						if (!LoginActivity.this.isFinishing())
							pd.dismiss();
						// 进入主页面
						Intent intent = new Intent(LoginActivity.this,
								MainActivity.class);
						intent.putExtra("status", "login");
						startActivity(intent);
						if(pd!=null)
							pd.dismiss();
						finish();
					}

					@Override
					public void onProgress(int progress, String status) {

					}

					@Override
					public void onError(int code, final String message) {
						runOnUiThread(new Runnable() {
							public void run() {
								if(pd!=null)
									pd.dismiss();
								Toast.makeText(getApplicationContext(), "注册失败，过会儿再试试？ " + message, 0).show();
							}
						});
					}
			});
			}
			
			
			
			super.onPostExecute(result);
		}
		String failString="";
		@Override
		protected Boolean doInBackground(String... params) {
			try {
				// 调用sdk注册方法
				EMChatManager.getInstance().createAccountOnServer(params[0], params[1]);
				// 保存用户名
				MyApplication.getInstance().setUserName(params[0]);
				return true;		
				}catch (final Exception e) {
					if (e != null && e.getMessage() != null) {
					failString=e.getMessage();
					}
			}
			return false;
		}
		
	}
}
